import { Table, Input, Button, Space, Select, Tag, Badge, Popconfirm, message, Divider, Card, Form, Tabs, Statistic, Row, Col, Modal, Progress, Dropdown, Upload, Typography, Radio } from '@/utils/antd-imports';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined, FilterOutlined, UserAddOutlined, CheckCircleOutlined, TeamOutlined, ArrowUpOutlined, ArrowDownOutlined, FileTextOutlined, ManOutlined, WomanOutlined, SolutionOutlined, HeartOutlined, BookOutlined, CalendarOutlined, ClockCircleOutlined, ProjectOutlined, DownOutlined, UploadOutlined, DownloadOutlined, ReloadOutlined } from '@/utils/icons';
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';





import DatePicker from 'antd/es/date-picker';














import moment from 'moment';
import employeeApi from '../../api/employeeApi'; // 导入API文件
import { dynamicImportApi } from '../../api/dynamicImportApi';
import { exportToExcel } from '../../utils/excelExport';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Text } = Typography;

// 定义状态常量
const EMPLOYEE_STATUS = {
  ONBOARD: 1, // 在职
  LEAVE: 0,   // 离职
  VACATION: 2 // 休假
};

const STATUS_MAP = {
  [EMPLOYEE_STATUS.ONBOARD]: { text: '在职', color: 'green' },
  [EMPLOYEE_STATUS.LEAVE]: { text: '离职', color: 'red' },
  [EMPLOYEE_STATUS.VACATION]: { text: '休假', color: 'orange' }
};

const EmployeeRoster = forwardRef(({ onMemberSelect }, ref) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [activeTab, setActiveTab] = useState('onboard');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [form] = Form.useForm();
  const [filterForm] = Form.useForm();
  const [showAdvancedFilter, setShowAdvancedFilter] = useState(false);
  const [stats, setStats] = useState({
    totalEmployees: 0,
    onboardEmployees: 0,
    leaveEmployees: 0,
    probationEmployees: 0,
    monthOnboard: 0,
    monthLeave: 0,
    departmentDistribution: {},
    employeeTypeDistribution: {},
    educationDistribution: {},
    politicalStatusDistribution: {},
    maritalStatusDistribution: {},
    genderRatio: { male: 0, female: 0 },
    contractStatus: { active: 0, expiring: 0, expired: 0 }
  });
  const [documentModalVisible, setDocumentModalVisible] = useState(false);
  const [currentDocument, setCurrentDocument] = useState('');
  const [currentDocumentContent, setCurrentDocumentContent] = useState('');

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    refreshData: () => {
      fetchData();
    }
  }));

  // 批量导入相关状态
  const [importVisible, setImportVisible] = useState(false);
  const [importMode, setImportMode] = useState('add'); // add 或 update
  const [importLoading, setImportLoading] = useState(false);
  const [importFile, setImportFile] = useState(null);

  // 管理按钮菜单项
  const managementMenuItems = [
    {
      key: 'add',
      label: '新增员工',
      icon: <UserAddOutlined />,
      onClick: () => {
        // 通知Dashboard创建新页签
        if (onMemberSelect) {
          onMemberSelect({
            type: 'create-employee',
            key: 'employee-form-create',
            label: '新增员工'
          });
        }
      }
    },
    {
      key: 'import',
      label: '批量导入',
      icon: <UploadOutlined />,
      onClick: () => {
        setImportVisible(true);
      }
    },
    {
      key: 'export',
      label: '批量导出',
      icon: <DownloadOutlined />,
      onClick: () => {
        handleExportEmployee();
      }
    },
    {
      key: 'refresh',
      label: '列表刷新',
      icon: <ReloadOutlined />,
      onClick: () => {
        fetchData();
        message.success('列表已刷新');
      }
    }
  ];

  // 获取数据
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      // 根据tab决定状态筛选条件
      let statusFilter = null;
      if (activeTab === 'onboard') {
        statusFilter = EMPLOYEE_STATUS.ONBOARD;
      } else if (activeTab === 'leave') {
        statusFilter = EMPLOYEE_STATUS.LEAVE;
      }
      
      let result;
      
      // 如果有状态筛选，使用新的状态查询API
      if (statusFilter !== null) {
        result = await employeeApi.getEmployeesByStatus(statusFilter);
        // 状态查询API返回的是数组，需要转换为分页格式
        const processedData = result.data || result;
        setData(Array.isArray(processedData) ? processedData : []);
        setPagination({
          ...pagination,
          total: Array.isArray(processedData) ? processedData.length : 0,
        });
      } else {
        // 构建查询参数
        const queryParams = {
          page: pagination.current,
          size: pagination.pageSize,
          ...searchParams,
        };
        
        // 调用分页查询接口
        result = await employeeApi.getEmployeeList(queryParams);
        
        // 确保result.data存在，如果没有则使用result本身
        const rawData = result.data || result;
        
        // 处理返回数据 - 如果是分页数据，直接使用
        let processedData = [];
        if (rawData && rawData.records && Array.isArray(rawData.records)) {
          // 分页接口返回的数据格式
          processedData = rawData.records;
          setPagination({
            ...pagination,
            current: rawData.current || pagination.current,
            pageSize: rawData.size || pagination.pageSize,
            total: rawData.total || 0,
          });
        } else if (Array.isArray(rawData)) {
          // 数组格式的数据
          processedData = rawData;
          setPagination({
            ...pagination,
            total: rawData.length,
          });
        } else {
          console.warn('员工数据格式异常:', rawData);
          processedData = [];
          setPagination({
            ...pagination,
            total: 0,
          });
        }
        
        setData(processedData);
      }
      
      // 更新统计信息 - 需要获取所有数据来计算统计
      await updateStatistics();
    } catch (error) {
      console.error('请求失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 应用筛选条件
  const applyFilters = (data, params) => {
    if (!Array.isArray(data)) return [];
    
    return data.filter(item => {
      // 根据tab筛选
      if (activeTab === 'onboard' && item.status != EMPLOYEE_STATUS.ONBOARD) return false;
      if (activeTab === 'leave' && item.status != EMPLOYEE_STATUS.LEAVE) return false;
      
      // 处理可能的null/undefined值
      const name = item.name || '';
      const projectCode = item.projectCode || '';
      const department = item.department || '';
      const employeeType = item.employeeType || '';
      const probation = item.probation || '';
      
      if (params.name && !name.includes(params.name)) return false;
      if (params.projectCode && !projectCode.includes(params.projectCode)) return false;
      if (params.department && department !== params.department) return false;
      if (params.status && item.status != params.status) return false;
      if (params.employeeType && employeeType !== params.employeeType) return false;
      if (params.probation && probation !== params.probation) return false;
      
      if (params.dateRange) {
        const [start, end] = params.dateRange;
        const hireDate = item.hireDate ? moment(item.hireDate) : null;
        
        if (start && (!hireDate || hireDate.isBefore(start, 'day'))) return false;
        if (end && (!hireDate || hireDate.isAfter(end, 'day'))) return false;
      }
      
      return true;
    });
  };

  // 更新统计信息
  const updateStatistics = async () => {
    try {
      // 获取所有员工数据用于统计
      const allEmployeesResult = await employeeApi.getEmployeeList({
        page: 1,
        size: 10000 // 获取大量数据用于统计
      });
      
      // 确保 employeeList 是数组
      let employeeList = [];
      if (allEmployeesResult && allEmployeesResult.data) {
        if (Array.isArray(allEmployeesResult.data.records)) {
          employeeList = allEmployeesResult.data.records;
        } else if (Array.isArray(allEmployeesResult.data)) {
          employeeList = allEmployeesResult.data;
        }
      } else if (Array.isArray(allEmployeesResult)) {
        employeeList = allEmployeesResult;
      }
      
      // 确保 employeeList 是数组，如果不是则设为空数组
      if (!Array.isArray(employeeList)) {
        console.warn('员工数据不是数组格式:', employeeList);
        employeeList = [];
      }
      
      console.log('获取到的员工数据总数:', employeeList.length);
      console.log('员工数据示例:', employeeList.slice(0, 3));
      
      // 使用 Number() 确保 status 是数字类型进行比较
      const onboardCount = employeeList.filter(e => Number(e.status) === EMPLOYEE_STATUS.ONBOARD).length;
      const leaveCount = employeeList.filter(e => Number(e.status) === EMPLOYEE_STATUS.LEAVE).length;
      const probationCount = employeeList.filter(e => (e.probation === '试用期' || e.probation === 'probation' || e.probation === '1') && Number(e.status) === EMPLOYEE_STATUS.ONBOARD).length;
      
      // 计算部门分布 - 只统计在职员工
      const departmentCount = {};
      // 计算婚姻状况分布 - 只统计在职员工
      const maritalStatusCount = {};
      // 计算政治面貌分布 - 只统计在职员工
      const politicalStatusCount = {};
      // 计算学历分布 - 只统计在职员工
      const educationCount = {};
      
      employeeList.filter(e => Number(e.status) === EMPLOYEE_STATUS.ONBOARD).forEach(item => {
        const department = item.department || '未知部门';
        departmentCount[department] = (departmentCount[department] || 0) + 1;
        
        // 婚姻状况统计
        const maritalStatus = item.maritalStatus || '未知';
        maritalStatusCount[maritalStatus] = (maritalStatusCount[maritalStatus] || 0) + 1;
        
        // 政治面貌统计
        const politicalStatus = item.politicalStatus || '未知';
        politicalStatusCount[politicalStatus] = (politicalStatusCount[politicalStatus] || 0) + 1;
        
        // 学历统计
        const education = item.education || '未知';
        educationCount[education] = (educationCount[education] || 0) + 1;
      });
      
      // 计算性别比例 - 只统计在职员工
      const genderCount = { male: 0, female: 0 };
      employeeList.filter(e => Number(e.status) === EMPLOYEE_STATUS.ONBOARD).forEach(item => {
        if (item.gender === '男' || item.gender === 'M') genderCount.male++;
        else if (item.gender === '女' || item.gender === 'F') genderCount.female++;
      });
      
      // 计算合同状态 - 只统计在职员工
      const contractStatus = { active: 0, expiring: 0, expired: 0 };
      employeeList.filter(e => Number(e.status) === EMPLOYEE_STATUS.ONBOARD).forEach(item => {
        if (!item.latestContractEnd) {
          contractStatus.active++; // 没有合同结束时间，默认视为正常
          return;
        }
        const endDate = moment(item.latestContractEnd);
        if (!endDate.isValid()) {
          contractStatus.active++; // 日期无效，默认视为正常
          return;
        }
        const now = moment();
        const daysRemaining = endDate.diff(now, 'days');
        
        if (daysRemaining < 0) contractStatus.expired++;
        else if (daysRemaining <= 30) contractStatus.expiring++;
        else contractStatus.active++;
      });

      // 计算本月入职和离职人数
      const monthOnboard = employeeList.filter(item => {
        if (!item.hireDate) return false;
        return moment(item.hireDate).isSame(moment(), 'month');
      }).length;
      
      const monthLeave = employeeList.filter(item => {
        if (Number(item.status) !== EMPLOYEE_STATUS.LEAVE) return false;
        if (!item.updateTime) return false;
        return moment(item.updateTime).isSame(moment(), 'month');
      }).length;

      setStats({
        totalEmployees: employeeList.length,
        onboardEmployees: onboardCount,
        leaveEmployees: leaveCount,
        probationEmployees: probationCount,
        monthOnboard: monthOnboard,
        monthLeave: monthLeave,
        departmentDistribution: departmentCount,
        maritalStatusDistribution: maritalStatusCount,
        politicalStatusDistribution: politicalStatusCount,
        educationDistribution: educationCount,
        genderRatio: genderCount,
        contractStatus: contractStatus,
      });
      
      console.log('统计结果:', {
        totalEmployees: employeeList.length,
        onboardEmployees: onboardCount,
        leaveEmployees: leaveCount,
        probationEmployees: probationCount,
        monthOnboard: monthOnboard,
        monthLeave: monthLeave,
        genderRatio: genderCount,
      });
    } catch (error) {
      console.error('更新统计信息失败:', error);
      // 设置默认统计信息，避免页面显示异常
      setStats(prevStats => ({
        ...prevStats,
        totalEmployees: 0,
        onboardEmployees: 0,
        leaveEmployees: 0,
        probationEmployees: 0,
        monthOnboard: 0,
        monthLeave: 0,
        departmentDistribution: {},
        employeeTypeDistribution: {},
        educationDistribution: {},
        politicalStatusDistribution: {},
        maritalStatusDistribution: {},
        genderRatio: { male: 0, female: 0 },
        contractStatus: { active: 0, expiring: 0, expired: 0 }
      }));
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, searchParams, activeTab]);

  // 查看文档
  const handleViewDocument = (documentName, content) => {
    setCurrentDocument(documentName);
    setCurrentDocumentContent(content);
    setDocumentModalVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      fixed: 'left',
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 120,
    },
    {
      title: '所属单位',
      dataIndex: 'clientUnit',
      key: 'clientUnit',
      width: 120,
    },
    {
      title: '所在部门',
      dataIndex: 'department',
      key: 'department',
      width: 120,
    },
    {
      title: '所在团队',
      dataIndex: 'team',
      key: 'team',
      width: 120,
    },
    {
      title: '岗位名称',
      dataIndex: 'position',
      key: 'position',
      width: 120,
    },
    {
      title: '员工类型',
      dataIndex: 'employeeType',
      key: 'employeeType',
      width: 100,
      render: type => {
        let color = '';
        switch (type) {
          case '正式员工':
            color = 'green';
            break;
          case '实习生':
            color = 'blue';
            break;
          case '见习生':
            color = 'orange';
            break;
          default:
            color = 'default';
        }
        return <Tag color={color}>{type}</Tag>;
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 60,
    },
    {
      title: '婚否',
      dataIndex: 'maritalStatus',
      key: 'maritalStatus',
      width: 60,
    },
    {
      title: '籍贯',
      dataIndex: 'nativePlace',
      key: 'nativePlace',
      width: 100,
    },
    {
      title: '民族',
      dataIndex: 'ethnicity',
      key: 'ethnicity',
      width: 80,
    },
    {
      title: '政治面貌',
      dataIndex: 'politicalStatus',
      key: 'politicalStatus',
      width: 100,
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      key: 'idCard',
      width: 180,
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      width: 100,
      render: date => moment(date).format('YYYY-MM-DD'),
    },
    {
      title: '户籍地址',
      dataIndex: 'registeredAddress',
      key: 'registeredAddress',
      width: 200,
    },
    {
      title: '现居住地址',
      dataIndex: 'currentAddress',
      key: 'currentAddress',
      width: 200,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '微信号',
      dataIndex: 'wechat',
      key: 'wechat',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '入职时间',
      dataIndex: 'hireDate',
      key: 'hireDate',
      width: 120,
      render: date => moment(date).format('YYYY-MM-DD'),
    },
    {
      title: '转正时间',
      dataIndex: 'confirmationDate',
      key: 'confirmationDate',
      width: 120,
      render: date => date ? moment(date).format('YYYY-MM-DD') : '-',
    },
    {
      title: '学历/学位',
      dataIndex: 'education',
      key: 'education',
      width: 100,
    },
    {
      title: '所学专业',
      dataIndex: 'major',
      key: 'major',
      width: 120,
    },
    {
      title: '毕业院校',
      dataIndex: 'university',
      key: 'university',
      width: 120,
    },
    {
      title: '毕业时间',
      dataIndex: 'graduationDate',
      key: 'graduationDate',
      width: 120,
      render: date => moment(date).format('YYYY-MM-DD'),
    },
    {
      title: '技能证书',
      dataIndex: 'skillCertificates',
      key: 'skillCertificates',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('技能证书', record.skillCertificates)}
        >
          查看
        </Button>
      ),
    },
    {
      title: '基本工资',
      dataIndex: 'baseSalary',
      key: 'baseSalary',
      width: 100,
    },
    {
      title: '紧急联系人',
      dataIndex: 'emergencyContact',
      key: 'emergencyContact',
      width: 120,
    },
    {
      title: '紧急联系电话',
      dataIndex: 'emergencyPhone',
      key: 'emergencyPhone',
      width: 140,
    },
    {
      title: '银行卡号',
      dataIndex: 'bankAccount',
      key: 'bankAccount',
      width: 180,
    },
    {
      title: '开户行',
      dataIndex: 'bankName',
      key: 'bankName',
      width: 120,
    },
    {
      title: '入职登记表',
      dataIndex: 'entryForm',
      key: 'entryForm',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('入职登记表', record.entryForm)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '身份证复印件',
      dataIndex: 'idCardCopy',
      key: 'idCardCopy',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('身份证复印件', record.idCardCopy)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '学历毕业证书',
      dataIndex: 'diploma',
      key: 'diploma',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('学历毕业证书', record.diploma)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '学位证书',
      dataIndex: 'degreeCertificate',
      key: 'degreeCertificate',
      width: 100,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('学位证书', record.degreeCertificate)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '银行卡复印件',
      dataIndex: 'bankCardCopy',
      key: 'bankCardCopy',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('银行卡复印件', record.bankCardCopy)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '简历',
      dataIndex: 'resume',
      key: 'resume',
      width: 100,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('简历', record.resume)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '离职证明',
      dataIndex: 'leavingCertificate',
      key: 'leavingCertificate',
      width: 100,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('离职证明', record.leavingCertificate)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '三甲体检报告',
      dataIndex: 'medicalReport',
      key: 'medicalReport',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('三甲体检报告', record.medicalReport)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '保密协议',
      dataIndex: 'confidentialityAgreement',
      key: 'confidentialityAgreement',
      width: 100,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('保密协议', record.confidentialityAgreement)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '员工培训协议',
      dataIndex: 'trainingAgreement',
      key: 'trainingAgreement',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('员工培训协议', record.trainingAgreement)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '规章制度确认书',
      dataIndex: 'rulesConfirmation',
      key: 'rulesConfirmation',
      width: 140,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('规章制度确认书', record.rulesConfirmation)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '员工行为准则',
      dataIndex: 'codeOfConduct',
      key: 'codeOfConduct',
      width: 120,
      render: (text, record) => (
        <Button 
          type="link" 
          icon={<FileTextOutlined />} 
          onClick={() => handleViewDocument('员工行为准则', record.codeOfConduct)}
        >
          {text}
        </Button>
      ),
    },
    {
      title: '是否已续签合同',
      dataIndex: 'contractRenewed',
      key: 'contractRenewed',
      width: 120,
    },
    {
      title: '续签合同次数',
      dataIndex: 'renewalCount',
      key: 'renewalCount',
      width: 120,
    },
    {
      title: '劳动合同开始时间',
      dataIndex: 'latestContractStart',
      key: 'latestContractStart',
      width: 140,
      render: date => moment(date).format('YYYY-MM-DD'),
    },
    {
      title: '劳动合同结束时间',
      dataIndex: 'latestContractEnd',
      key: 'latestContractEnd',
      width: 140,
      render: date => moment(date).format('YYYY-MM-DD'),
    },
    {
      title: '签合同公司',
      dataIndex: 'contractCompany',
      key: 'contractCompany',
      width: 120,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      fixed: 'right',
      render: status => {
        const statusInfo = STATUS_MAP[status] || { text: '未知', color: 'default' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          />
          {activeTab === 'onboard' && record.probation === '试用期' && (
            <Button 
              type="text" 
              icon={<CheckCircleOutlined />} 
              onClick={() => handleConfirm(record.id)}
            />
          )}
          <Popconfirm
            title="确定要删除此员工吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination({
      ...pagination,
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  // 处理搜索
  const handleSearch = values => {
    setSearchParams(values);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 编辑员工
  const handleEdit = record => {
    if (onMemberSelect) {
      onMemberSelect({
        type: 'edit-employee',
        key: `employee-form-edit-${record.id}`,
        label: `编辑-${record.name}`,
        employeeId: record.id,
        mode: 'edit'
      });
    }
  };

  // 删除员工
  const handleDelete = async (id) => {
    try {
      await employeeApi.deleteEmployee(id);
      message.success('员工删除成功');
      fetchData(); // 刷新数据
    } catch (error) {
      console.error('删除员工失败:', error);
      message.error('删除员工失败，请重试');
    }
  };

  // 新增员工 - 现在通过Dashboard页签处理
  const handleAdd = () => {
    if (onMemberSelect) {
      onMemberSelect({
        type: 'create-employee',
        key: 'employee-form-create',
        label: '新增员工'
      });
    }
  };

  // 员工转正
  const handleConfirm = id => {
    message.success(`员工ID：${id} 已转正`);
    // 这里应该调用API转正员工
    fetchData();
  };

  // 导出员工数据
  const handleExportEmployee = () => {
    if (!data || data.length === 0) {
      message.warning('没有数据可导出');
      return;
    }
    
    try {
      // 准备导出的数据，处理日期格式
      const exportData = data.map(item => ({
        ...item,
        birthday: item.birthday ? moment(item.birthday).format('YYYY-MM-DD') : '',
        hireDate: item.hireDate ? moment(item.hireDate).format('YYYY-MM-DD') : '',
        confirmationDate: item.confirmationDate ? moment(item.confirmationDate).format('YYYY-MM-DD') : '',
        graduationDate: item.graduationDate ? moment(item.graduationDate).format('YYYY-MM-DD') : '',
        latestContractStart: item.latestContractStart ? moment(item.latestContractStart).format('YYYY-MM-DD') : '',
        latestContractEnd: item.latestContractEnd ? moment(item.latestContractEnd).format('YYYY-MM-DD') : '',
      }));
      
      const filename = `员工花名册_${moment().format('YYYYMMDD_HHmmss')}.xlsx`;
      exportToExcel(exportData, columns, filename);
      message.success('员工数据导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    }
  };


  // 切换tab
  const handleTabChange = key => {
    setActiveTab(key);
    setPagination({
      ...pagination,
      current: 1,
    });
  };


  return (
    <div style={{ padding: 24 }}>
      {/* 统计指标看板 */}
      <Card bordered={false} style={{ marginBottom: 16 }}>
        {activeTab === 'onboard' ? (
          <>
            <div style={{ overflowX: 'auto', marginBottom: 16 }}>
              <div style={{ display: 'flex', minWidth: 'max-content' }}>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="在职员工总数"
                      value={stats.onboardEmployees}
                      prefix={<TeamOutlined />}
                      valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="试用期员工"
                      value={stats.probationEmployees}
                      prefix={<TeamOutlined />}
                      valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="本月入职"
                      value={stats.monthOnboard}
                      prefix={<ArrowUpOutlined />}
                      valueStyle={{ color: '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="男性员工"
                      value={stats.genderRatio.male}
                      prefix={<ManOutlined />}
                      valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="女性员工"
                      value={stats.genderRatio.female}
                      prefix={<WomanOutlined />}
                      valueStyle={{ color: '#eb2f96', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="已婚员工"
                      value={stats.maritalStatusDistribution['已婚'] || 0}
                      prefix={<HeartOutlined />}
                      valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
              </div>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <div style={{ display: 'flex', minWidth: 'max-content' }}>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="党员人数"
                      value={stats.politicalStatusDistribution['党员'] || 0}
                      prefix={<SolutionOutlined />}
                      valueStyle={{ color: '#f5222d', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="本科及以上"
                      value={(stats.educationDistribution['本科'] || 0) + 
                            (stats.educationDistribution['硕士'] || 0) + 
                            (stats.educationDistribution['博士'] || 0)}
                      prefix={<BookOutlined />}
                      valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="合同正常"
                      value={stats.contractStatus.active}
                      prefix={<CalendarOutlined />}
                      valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '180px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="合同即将到期"
                      value={stats.contractStatus.expiring}
                      prefix={<ClockCircleOutlined />}
                      valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px', marginRight: 16 }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <Statistic
                      title="合同已过期"
                      value={stats.contractStatus.expired}
                      prefix={<ClockCircleOutlined />}
                      valueStyle={{ color: '#f5222d', fontSize: '24px', fontWeight: 'bold' }}
                    />
                  </Card>
                </div>
                <div style={{ minWidth: '150px' }}>
                  <Card size="small" style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: '14px', color: '#666', marginBottom: 8 }}>性别比例</div>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff' }}>
                      男：{stats.genderRatio.male} / 女：{stats.genderRatio.female}
                    </div>
                  </Card>
                </div>
              </div>
            </div>
          </>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <div style={{ display: 'flex', minWidth: 'max-content' }}>
              <div style={{ minWidth: '180px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="离职员工总数"
                    value={stats.leaveEmployees}
                    prefix={<TeamOutlined />}
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '150px', marginRight: 16 }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="本月离职"
                    value={stats.monthLeave}
                    prefix={<ArrowDownOutlined />}
                    valueStyle={{ color: '#cf1322', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
              <div style={{ minWidth: '150px' }}>
                <Card size="small" style={{ textAlign: 'center' }}>
                  <Statistic
                    title="员工总数"
                    value={stats.totalEmployees}
                    prefix={<TeamOutlined />}
                    valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                  />
                </Card>
              </div>
            </div>
          </div>
        )}
      </Card>

      {/* 功能按钮区域 */}
      <Card bordered={false} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space>
            <Dropdown
              menu={{ items: managementMenuItems }}
              trigger={['click']}
            >
              <Button type="primary" icon={<DownOutlined />}>
                管理
              </Button>
            </Dropdown>
            <Button icon={<SyncOutlined />} onClick={() => fetchData()}>
              刷新
            </Button>
          </Space>
          
          <Space>
            <Button 
              icon={<FilterOutlined />}
              onClick={() => setShowAdvancedFilter(!showAdvancedFilter)}
            >
              {showAdvancedFilter ? '收起筛选' : '更多筛选'}
            </Button>
          </Space>
        </div>
      </Card>

      {/* Tab切换区域 */}
      <Card bordered={false}>
        <Tabs 
          type="card" 
          activeKey={activeTab} 
          onChange={handleTabChange}
        >
          <TabPane tab="在职人员" key="onboard" />
          <TabPane tab="离职人员" key="leave" />
        </Tabs>

        {/* 基础筛选区域 */}
        <Form
          form={form}
          onFinish={handleSearch}
          layout="inline"
          initialValues={{
            status: '',
            employeeType: '',
            probation: '',
          }}
          style={{ marginTop: 16 }}
        >
          <Row gutter={[16, 16]} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item name="name" label="员工姓名" style={{ width: '100%' }}>
                <Input placeholder="请输入员工姓名" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="projectCode" label="项目编号" style={{ width: '100%' }}>
                <Input placeholder="请输入项目编号" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="department" label="所在部门" style={{ width: '100%' }}>
                <Select placeholder="请选择部门" allowClear>
                  <Option value="研发部">研发部</Option>
                  <Option value="市场部">市场部</Option>
                  <Option value="人事部">人事部</Option>
                  <Option value="财务部">财务部</Option>
                  <Option value="行政部">行政部</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={() => form.resetFields()}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>

        {/* 高级筛选区域 */}
        {showAdvancedFilter && (
          <Card size="small" style={{ marginTop: 16 }}>
            <Form
              form={filterForm}
              layout="inline"
              style={{ marginTop: 8 }}
            >
              <Row gutter={[16, 16]} style={{ width: '100%' }}>
                <Col span={6}>
                  <Form.Item name="education" label="学历" style={{ width: '100%' }}>
                    <Select placeholder="请选择学历" allowClear>
                      <Option value="博士">博士</Option>
                      <Option value="硕士">硕士</Option>
                      <Option value="本科">本科</Option>
                      <Option value="专科">专科</Option>
                      <Option value="高中">高中</Option>
                      <Option value="初中">初中</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="major" label="专业" style={{ width: '100%' }}>
                    <Select placeholder="请选择专业" allowClear>
                      <Option value="计算机科学与技术">计算机科学与技术</Option>
                      <Option value="软件工程">软件工程</Option>
                      <Option value="信息管理与信息系统">信息管理与信息系统</Option>
                      <Option value="工商管理">工商管理</Option>
                      <Option value="市场营销">市场营销</Option>
                      <Option value="财务管理">财务管理</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="university" label="院校" style={{ width: '100%' }}>
                    <Select placeholder="请选择院校" allowClear>
                      <Option value="清华大学">清华大学</Option>
                      <Option value="北京大学">北京大学</Option>
                      <Option value="北京理工大学">北京理工大学</Option>
                      <Option value="北京邮电大学">北京邮电大学</Option>
                      <Option value="其他">其他</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="gender" label="性别" style={{ width: '100%' }}>
                    <Select placeholder="请选择性别" allowClear>
                      <Option value="男">男</Option>
                      <Option value="女">女</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={[16, 16]} style={{ width: '100%', marginTop: 8 }}>
                <Col span={6}>
                  <Form.Item name="maritalStatus" label="婚否" style={{ width: '100%' }}>
                    <Select placeholder="请选择婚姻状况" allowClear>
                      <Option value="未婚">未婚</Option>
                      <Option value="已婚">已婚</Option>
                      <Option value="离异">离异</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="unit" label="所属单位" style={{ width: '100%' }}>
                    <Select placeholder="请选择所属单位" allowClear>
                      <Option value="总公司">总公司</Option>
                      <Option value="分公司A">分公司A</Option>
                      <Option value="分公司B">分公司B</Option>
                      <Option value="子公司">子公司</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="probation" label="转正状态" style={{ width: '100%' }}>
                    <Select placeholder="请选择转正状态" allowClear>
                    <Option value="试用期">试用期</Option>
                    <Option value="已转正">已转正</Option>
                  </Select>
                </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="employeeType" label="人员类型" style={{ width: '100%' }}>
                    <Select placeholder="请选择人员类型" allowClear>
                      <Option value="正式员工">正式员工</Option>
                      <Option value="实习生">实习生</Option>
                      <Option value="见习生">见习生</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              
              <Row gutter={[16, 16]} style={{ width: '100%', marginTop: 8 }}>
                <Col span={6}>
                  <Form.Item name="dateRange" label={activeTab === 'onboard' ? '入职日期' : '离职日期'} style={{ width: '100%' }}>
                    <RangePicker style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>
          
          <Row gutter={[16, 16]} style={{ width: '100%', marginTop: 8 }}>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleReset} icon={<SyncOutlined />}>
                    重置
                  </Button>
                  <Button type="dashed" icon={<FilterOutlined />}>
                    更多筛选
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
          </Card>
        )}

        {/* 表格区域 */}
        <div style={{ marginTop: 16 }}>
          <Table
            columns={columns}
            rowKey="id"
            dataSource={data}
            loading={loading}
            pagination={pagination}
            onChange={handleTableChange}
            scroll={{ x: 5000 }}
            bordered
            size="middle"
          />
        </div>
      </Card>

      {/* 文档查看模态框 */}
      <Modal
        title={`查看${currentDocument}`}
        visible={documentModalVisible}
        onCancel={() => setDocumentModalVisible(false)}
        footer={null}
        width={800}
      >
        <div style={{ height: '500px', overflow: 'auto' }}>
          <pre>{currentDocumentContent}</pre>
        </div>
      </Modal>

      {/* 批量导入对话框 */}
      <Modal
        title="批量导入员工"
        visible={importVisible}
        width={600}
        onOk={async () => {
          if (!importFile) {
            message.warning('请先选择Excel文件');
            return;
          }

          setImportLoading(true);
          try {
            const response = importMode === 'add' 
              ? await dynamicImportApi.importEmployee(importFile)
              : await dynamicImportApi.importEmployeeWithUpdate(importFile);
            
            if (response.code === 200) {
              const data = response.data;
              message.success(
                `导入完成：成功 ${data.successCount || 0} 条，更新 ${data.updateCount || 0} 条，失败 ${data.failCount || 0} 条`
              );
              setImportVisible(false);
              fetchData();
            } else {
              message.error(response.message || '导入失败');
            }
          } catch (error) {
            console.error('导入失败:', error);
            message.error('导入失败: ' + (error.message || '未知错误'));
          } finally {
            setImportLoading(false);
          }
        }}
        onCancel={() => setImportVisible(false)}
        okText="开始导入"
        cancelText="取消"
        confirmLoading={importLoading}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <div>
            <Text>导入模式：</Text>
            <Radio.Group value={importMode} onChange={(e) => setImportMode(e.target.value)} style={{ marginLeft: 8 }}>
              <Radio value="add">新增模式（已存在则跳过）</Radio>
              <Radio value="update">更新模式（已存在则更新）</Radio>
            </Radio.Group>
          </div>
          <Upload
            accept=".xlsx,.xls"
            beforeUpload={(file) => {
              setImportFile(file);
              return false;
            }}
            showUploadList={true}
            maxCount={1}
          >
            <Button icon={<UploadOutlined />} loading={importLoading}>
              选择Excel文件
            </Button>
          </Upload>
          <div style={{ color: '#999', fontSize: '12px' }}>
            <div>• 支持 .xlsx 和 .xls 格式</div>
            <div>• 第一行为表头（中文列名）</div>
            <div>• 支持灵活的列顺序</div>
            <div>• 系统会自动匹配字段</div>
          </div>
        </Space>
      </Modal>
    </div>
  );
});

export default EmployeeRoster;